const express = require('express');
//引入jwt相关的包
const jwt = require('jsonwebtoken');
const expressJWT = require('express-jwt');
//2.定义密钥
const secretKey = 'secret12345';

const app = express();
//定义解析token

app.use(express.static('./view'))//
//接口不需要访问权限
app.use(expressJWT({ secret: secretKey }).unless({ path: [/^\/api/] }))

//3.定义一个登录接口expressJwt
app.post('/api/login', (req, res) => {
    const user = { username: 'test001' }
    const tokenStr = jwt.sign(user, secretKey, { expiresIn: '10s' })
    res.send({
        status: 200,
        message: '登入成功',
        //生成jwt字符串 三个参数：用户对象、加密密钥、配置对象
        token: 'Bearer ' + tokenStr,
    })
})
//获取用户信息
app.get('/my/getinfo', (req, res) => {
    console.log(req.user);
    res.send({
        status: 200,
        message: '获取用户信息成功！',
        data: req.user
    })
})

app.use((err, req, res, next) => {
    if (err.name == 'UnauthorizedError') {
        return res.send({
            status: 401,
            message: '无效token'
        })
    }
    //其他原因导致的错误
    res.send({
        status: 500,
        message: '未知的错误！'
    })

})

app.listen(89, () => {
    console.log('http://127.0.0.1:89');
})
